layui.config({base: '/js/lib/'}).extend({fileupload: 'fileupload'}).use(['layer','form','table','fileupload'], function() {
    var layer = layui.layer, form = layui.form,table = layui.table,fileupload = layui.fileupload;
    $('.sel-load').selLoad(function () {
        var user = app.obtainUser();
        form.val('baseForm',{'salePersonId':user.personId,'busPersonId':user.personId});
        form.render('select');
    });
    deliveryInfoList([]);
    abroadDeliveryInfoList([]);
    bankList([]);
    table.on('tool(delivery-info-list)', function(obj){
        var data = obj.data;
        if(obj.event === 'deDel'){
            layer.confirm('您确定要删除此地址？', function(index){
                obj.del();
                deliveryInfoList(obtainDeliveryData());
                layer.close(index);
            });
        }
    });
    table.on('tool(abroad-delivery-info-list)', function(obj){
        var data = obj.data;
        if(obj.event === 'deDelAbroad'){
            layer.confirm('您确定要删除此地址？', function(index){
                obj.del();
                abroadDeliveryInfoList(obtainAbroadDeliveryData());
                layer.close(index);
            });
        }
    });
    table.on('tool(bank-list)', function(obj){
        var data = obj.data;
        if(obj.event === 'deDel'){
            layer.confirm('您确定要删除此银行信息？', function(index){
                obj.del();
                bankList(obtainBankData());
                layer.close(index);
            });
        }
    });
    var fileObj = {docId:'temp_'+uuid(), docType:'customer'};
    fileupload.render({elem:'#cus_business',startQuery:false,uploadArg:{data:$.extend({},fileObj,{businessType:'cus_business'})}});
    fileupload.render({elem:'#cus_invoice',startQuery:false,uploadArg:{data:$.extend({},fileObj,{businessType:'cus_invoice'})}});
    fileupload.render({elem:'#cus_legal_id',startQuery:false,uploadArg:{data:$.extend({},fileObj,{businessType:'cus_legal_id'})}});
    fileupload.render({elem:'#cus_other',startQuery:false,uploadArg:{data:$.extend({},fileObj,{businessType:'cus_other'})}});
    var saveData = function (isSubmit){
        if(checkedForm($('.tsf-page-content'))){
            show_loading();
            var customer = $('#baseForm').serializeJson(),deliverys = obtainDeliveryData(),abroadDeliverys = obtainAbroadDeliveryData();
            var banks = obtainBankData();
            customer['isSubmit'] = isSubmit;
            postJSON('scm/customer/add',{"customer":customer,"deliverys":deliverys,"abroadDeliverys":abroadDeliverys,banks:banks,"file":fileObj},function (res) {
                parent.reloadList();
                closeThisWin('添加成功');
            });
        }
    };
    $('.save-btn').click(function () {
        saveData(false);
    });
    $('.examine-btn').click(function () {
        saveData(true);
    });

    $('#name').enter(function (){searchCss('3',$(this).val());});
    $('#socialNo').enter(function(){searchCss('1',$(this).val());});
    /*
    $('#name').autocomplete({
        source: function (request, response) {
            $.get(rurl('scm/company/vagueSimpleBusinessQuery'),{name: trim(request.term)},function (res) {
                response($.map(res.data, function (item) {return {label: item.name+' '+item.creditCode+' '+item.operName, value: item.name, data: item}}));
            });
        }, minLength: 0,autoFocus:true, delay: 300,
        select: function( event, ui ) {
            var data = ui.item.data;
            form.val('baseForm',{
                name: data.name,
                socialNo: data.creditCode,
                taxpayerNo: data.creditCode,
                legalPerson: data.operName
            });
        }
    }).focus(function () {
        $(this).select().autocomplete("search");
    });
     */
});
function searchCss(queryFlag,enterCode){
    if(isEmpty(enterCode)){return;}show_loading();$.ajax({url: rurl('scm/css/search'), data: JSON.stringify({'queryFlag':queryFlag,'enterCode':trim(enterCode)}), type: 'post', dataType: 'json', contentType: 'application/json', success: function (res){
            if(isSuccessNoTip(res)&&res.data!=null){
                $('#name').val(res.data.name);
                $('#socialNo').val(res.data.id);
                $('#customsCode').val(res.data.customsCode);
                $('#ciqNo').val(res.data.ciqCode);
            }}});
}
function deliveryInfoList(data) {
    layui.table.render({
        elem: '#delivery-info-list',limit:1000,id:'delivery-info-list',text:{none:'<a href="javascript:" class="def-a" onclick="addDelivery()"><i class="fa fa-plus-circle"></i>添加一行</a>'}
        ,cols: [[
            {type: 'numbers', title: '序号', width: 50,align:'center',fixed:true}
            ,{field: 'companyName', title: '收发货公司', width: 240,align:'form',templet:'#companyNameTemp'}
            ,{field: 'linkPerson', title: '联系人', width: 90,align:'form',templet:'#linkPersonTemp'}
            ,{field: 'linkTel', title: '联系电话', width: 110,align:'form',templet:'#linkTelTemp'}
            ,{field: 'area', title: '收发货区域', width: 200,align:'form',templet:'#areaTemp'}
            ,{field: 'address', title: '详细地址',align:'form',templet:'#addressTemp'}
            ,{field: 'disabled', title: '状态', width: 80,align:'form-switch',templet:'#disabledTemp'}
            ,{field: 'isDefault', title: '默认', width: 65,align:'center',templet:'#isDefaultTemp'}
            ,{field: 'oper', title: '操作', width: 65,toolbar: '#deOperaBar',fixed: 'right',align:'center'}
        ]]
        ,data: data
        ,done:function () {
            initCity('.area');
        }
    });
}
function abroadDeliveryInfoList(data) {
    layui.table.render({
        elem: '#abroad-delivery-info-list',limit:1000,id:'abroad-delivery-info-list',text:{none:'<a href="javascript:" class="def-a" onclick="addAbroadDelivery()"><i class="fa fa-plus-circle"></i>添加一行</a>'}
        ,cols: [[
            {type: 'numbers', title: '序号', width: 50,align:'center',fixed:true}
            ,{field: 'companyName', title: '收货公司', width: 240,align:'form',templet:'#companyNameTemp'}
            ,{field: 'linkPerson', title: '联系人', width: 90,align:'form',templet:'#linkPersonTemp'}
            ,{field: 'linkTel', title: '联系电话', width: 110,align:'form',templet:'#linkTelTemp'}
            ,{field: 'area', title: '收发货区域', width: 200,align:'form',templet:'#areaTemp'}
            ,{field: 'address', title: '详细地址',align:'form',templet:'#addressTemp'}
            ,{field: 'disabled', title: '状态', width: 80,align:'form-switch',templet:'#disabledTemp'}
            ,{field: 'isDefault', title: '默认', width: 65,align:'center',templet:'#isDefaultTemp'}
            ,{field: 'oper', title: '操作', width: 65,toolbar: '#deOperaAbroadBar',fixed: 'right',align:'center'}
        ]]
        ,data: data
        ,done:function () {
            initCity('.area');
        }
    });
}
//渲染银行数据
function bankList(data) {
    layui.table.render({
        elem: '#bank-list',limit:1000,id:'bank-list',text:{none:'<a href="javascript:" class="def-a" onclick="addBank()"><i class="fa fa-plus-circle"></i>添加一行</a>'}
        ,cols: [[
            {type: 'numbers', title: '序号', width: 50,align:'center',fixed:true}
            ,{field: 'name', title: '银行名称', width: 240,align:'form',templet:'#bankNameTemp'}
            ,{field: 'account', title: '账号', width: 160,align:'form',templet:'#bankAccountTemp'}
            ,{field: 'address', title: '详细地址',align:'form',templet:'#bankAddressTemp'}
            ,{field: 'disabled', title: '状态', width: 80,align:'form-switch',templet:'#disabledTemp'}
            ,{field: 'isDefault', title: '默认', width: 65,align:'center',templet:'#isDefaultTemp'}
            ,{field: 'oper', title: '操作', width: 65,toolbar: '#deOperaBar',fixed: 'right',align:'center'}
        ]]
        ,data: data
        ,done:function () {

        }
    });
}
function addDelivery() {
    var data = obtainDeliveryData();
    data.push({id:'', companyName:'', linkPerson:'', linkTel:'', area:'', address:'', disabled:false, isDefault:(data.length==0)?true:false});
    deliveryInfoList(data);
}
function addAbroadDelivery() {
    var data = obtainAbroadDeliveryData();
    data.push({id:'', companyName:'', linkPerson:'', linkTel:'', area:'', address:'', disabled:false, isDefault:(data.length==0)?true:false});
    abroadDeliveryInfoList(data);
}
//新增银行
function addBank() {
    var data = obtainBankData();
    data.push({id:'',name:'',account:'',address:'',disabled:false,isDefault:(data.length==0)?true:false});
    bankList(data);
}
function obtainBankData() {
    var data = []
        ,$bankForm = $('#bankForm')
        ,$ids = $bankForm.find('input[name="id"]')
        ,$names = $bankForm.find('input[name="name"]')
        ,$accounts = $bankForm.find('input[name="account"]')
        ,$addresss = $bankForm.find('input[name="address"]')
        ,$disableds = $bankForm.find('input[name="disabled"]')
        ,$isDefaults = $bankForm.find('input[name="isDefault"]');
    for(var i=0;i<$ids.size();i++){
        let disabled = ($($disableds[i]).parent().find('.layui-form-onswitch').size()>0)?false:true;
        var item = {
            id:$($ids[i]).val(),
            name:$($names[i]).val(),
            account:$($accounts[i]).val(),
            address:$($addresss[i]).val(),
            disabled:disabled,
            isDefault:($($isDefaults[i]).parent().find('.layui-form-radioed').size()>0) && disabled != true ?true:false
        }
        data.push(item);
    }
    return data;
}
function obtainDeliveryData() {
    var data = []
    ,$deliveryForm = $('#deliveryForm')
    ,$ids = $deliveryForm.find('input[name="id"]')
    ,$companyNames = $deliveryForm.find('input[name="companyName"]')
    ,$linkPersons = $deliveryForm.find('input[name="linkPerson"]')
    ,$linkTels = $deliveryForm.find('input[name="linkTel"]')
    ,$areas = $deliveryForm.find('input[name="area"]')
    ,$addresss = $deliveryForm.find('input[name="address"]')
    ,$disableds = $deliveryForm.find('input[name="disabled"]')
    ,$isDefaults = $deliveryForm.find('input[name="isDefault"]');
    for(var i=0;i<$ids.size();i++){
        let disabled = ($($disableds[i]).parent().find('.layui-form-onswitch').size()>0)?false:true;
        var item = {
            id:$($ids[i]).val(),
            companyName:$($companyNames[i]).val(),
            linkPerson:$($linkPersons[i]).val(),
            linkTel:$($linkTels[i]).val(),
            area:$($areas[i]).val(),
            provinceName:'',
            cityName:'',
            areaName:'',
            address:$($addresss[i]).val(),
            disabled:disabled,
            isDefault:($($isDefaults[i]).parent().find('.layui-form-radioed').size()>0) && disabled != true?true:false
        }
        if(!isEmpty(item.area)){
            var areas = item.area.split(" / ");
            item.provinceName = areas[0];
            item.cityName = areas[1];
            item.areaName = areas[2];
        }
        data.push(item);
    }
    return data;
}
function obtainAbroadDeliveryData() {
    var data = []
        ,$deliveryForm = $('#abroadDeliveryForm')
        ,$ids = $deliveryForm.find('input[name="id"]')
        ,$companyNames = $deliveryForm.find('input[name="companyName"]')
        ,$linkPersons = $deliveryForm.find('input[name="linkPerson"]')
        ,$linkTels = $deliveryForm.find('input[name="linkTel"]')
        ,$areas = $deliveryForm.find('input[name="area"]')
        ,$addresss = $deliveryForm.find('input[name="address"]')
        ,$disableds = $deliveryForm.find('input[name="disabled"]')
        ,$isDefaults = $deliveryForm.find('input[name="isDefault"]');
    for(var i=0;i<$ids.size();i++){
        let disabled = ($($disableds[i]).parent().find('.layui-form-onswitch').size()>0)?false:true;
        var item = {
            id:$($ids[i]).val(),
            companyName:$($companyNames[i]).val(),
            linkPerson:$($linkPersons[i]).val(),
            linkTel:$($linkTels[i]).val(),
            area:$($areas[i]).val(),
            provinceName:'',
            cityName:'',
            areaName:'',
            address:$($addresss[i]).val(),
            disabled:disabled,
            isDefault:($($isDefaults[i]).parent().find('.layui-form-radioed').size()>0) && disabled != true ?true:false
        }
        if(!isEmpty(item.area)){
            var areas = item.area.split(" / ");
            item.provinceName = areas[0];
            item.cityName = areas[1];
            item.areaName = areas[2];
        }
        data.push(item);
    }
    return data;
}
